/*
 * @Date: 2024-01-09 15:14:05
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-10 09:51:51
 * @FilePath: \chlor-alkali-cloud-mobile-end\src\store\index.tsx
 * @Description:
 */
import Taro, { useLaunch, getCurrentInstance } from "@tarojs/taro";
import React, { createContext, useContext, useEffect, useState } from "react";
import { setLocale } from "@/i18next/method";
import { getMenuButtonBoundingClientRectCompat } from "@/utils/common";
import SupRequest from "@/utils/api";

const GlobalDataContext = createContext<any>(null);

export function useGlobalData() {
  return useContext(GlobalDataContext);
}

export function GlobalDataProvider({ children }) {
  const [globalData, setGlobalData] = useState({});
  const [useInfo, setUseInfo] = useState({});
  const [isLogin, setIsLogin] = useState(false);

  const handleUserAuth = async () => {
    // console.log("handleUserAuth");
    // if (!window.h5sdk) {
    //   console.log("invalid h5sdk");
    //   return;
    // }
    // window.h5sdk.error((err) => {
    //   throw ("h5sdk error:", JSON.stringify(err));
    // });
    const res = await Taro.request({
      url: `/open-apis/auth/v3/app_access_token/internal`,
      method: "POST",
      header: {
        "content-type": "application/json; charset=utf-8",
      },
      // mode: "no-cors",
      data: {
        app_id: "cli_a5fc07626fba500b",
        app_secret: "JRYtx50HnHPWESiMUIXlsbIylBPQY4R6",
      },
    });
    console.log("app_access_token", res);
    // window.h5sdk.ready(() => {
    //   console.log("window.h5sdk.ready");
    //   console.log("url:", window.location.href);
    //   // ready 方法不需要每次都调用。
    //   window.tt.requestAuthCode({
    //     appId: "cli_a5fc07626fba500b",
    //     success: (info) => {
    //       console.log("getAuthCode succeed");
    //       console.info(info.code);
    //     },
    //     fail: (error) => {
    //       console.log(`getAuthCode failed, err:`, JSON.stringify(err));
    //     },
    //   });
    // });
  };

  useLaunch(() => {
    // 获取系统信息
    const systemInfo = Taro.getSystemInfoSync();
    // 获取状态栏高度
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    // 获取胶囊按钮位置信息
    const menuButtonInfo = getMenuButtonBoundingClientRectCompat();
    const menuButtonHeight = menuButtonInfo.height;
    const menuButtonTop = menuButtonInfo.top;
    const navbarHeight =
      (menuButtonTop - statusBarHeight) * 2 + menuButtonHeight;
    // 获取当前环境
    const env = Taro.getEnv();

    // 语言格式统一处理
    let language = systemInfo.language;
    console.log(language);
    if (!language) {
      // 提供一个默认值
      language = "en-us";
    } else {
      // 标准化语言代码
      // 一般来说，小程序平台返回的是zh_CN这种格式，而浏览器往往返回的是zh-CN这种格式
      // 这里可以根据需要将其转化为统一格式
      language = language.replace(/_/g, "-").toLowerCase();
    }
    // 设置当前语言
    setLocale(language);
    setGlobalData({
      systemInfo: { ...systemInfo, language, navbarHeight, env },
    });
    Taro.setStorageSync("language", language);
    setGlobalData({
      systemInfo: { ...systemInfo, language, navbarHeight, env },
    });

    const token = Taro.getStorageSync("token");
    setIsLogin(token ? true : false);
    handleUserAuth();
  });

  // 提供全局数据的 setter 函数
  const setGlobal = (data) => {
    setGlobalData((prevGlobalData) => ({
      ...prevGlobalData,
      ...data,
    }));
  };

  return (
    <GlobalDataContext.Provider
      value={{
        ...globalData,
        setGlobal,
        useInfo,
        setUseInfo,
        isLogin,
        setIsLogin,
      }}
    >
      {children}
    </GlobalDataContext.Provider>
  );
}
